﻿using System;
using System.Collections.Generic;
using System.Text;
using Cemit.PolyProto;
using Google.Protobuf;

namespace Cemit.PolyServer.Main
{
    /// <summary>
    /// 接收Msg_Main_GetLobby消息，返回所有已注册的大厅服务器信息
    /// </summary>
    class GetLobbyListHandle : IMessageHandle<Msg_Main_GetLobbyList>
    {
        private const string LOBBY_LIST_FILE = "LobbyServerList";
        private const string LOBBY_INFO_NAME_KEY = "name";
        private const string LOBBY_INFO_IP_KEY = "ip"; 

        public void Execute(ClientState clientState, IMessage message)
        {
            JsonConfigs configs = Jsons.Get(LOBBY_LIST_FILE);
            Msg_Main_LobbyInfoList msg = new Msg_Main_LobbyInfoList();
            foreach (var item in configs.GetKeys())
            {
                string ipText = configs.GetValue($"{item}:{LOBBY_INFO_IP_KEY}");
                string[] ipAndPort = ipText.Split(":");
                if (ipAndPort.Length != 2)
                {
                    throw new Exception(LOBBY_LIST_FILE + "配置文件有误！");
                }
                msg.ServerInfoList.Add(new LobbyInfo
                {
                    Id = int.TryParse(item, out int id) ? id : -1,
                    Name = configs.GetValue($"{item}:{LOBBY_INFO_NAME_KEY}"),
                    Ip = ipAndPort[0],
                    Port = int.TryParse(ipAndPort[1], out int port) ? port : -1,
                });
            }

            clientState.Send(msg);
        }
    }
}
